package com.heubu.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.heubu.mall.dao.ProductMapper;
import com.heubu.mall.pojo.Product;
import com.heubu.mall.service.ICategoryService;
import com.heubu.mall.service.IProductService;
import com.heubu.mall.vo.ProductDetailVo;
import com.heubu.mall.vo.ProductVo;
import com.heubu.mall.vo.ResponseVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

import static com.heubu.mall.enums.ProductStatusEnum.DELETE;
import static com.heubu.mall.enums.ProductStatusEnum.OFF_SALE;
import static com.heubu.mall.enums.ResponseEnum.PRODUCT_OFF_SALE_OR_DELETE;

/**
 * @Author Wangchuang
 * @Date: 2022/5/5 23:42
 * @Version 1.0
 * @Description:
 */
@Service
public class ProductServiceImpl implements IProductService {
    
    @Autowired
    private ProductMapper productMapper;
    
    @Autowired
    private ICategoryService categoryService;
    
    /**
     * 商品列表
     *
     * @param categoryId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ResponseVo<PageInfo> list(Integer categoryId, Integer pageNum, Integer pageSize) {
        HashSet<Integer> categoryIdSet = new HashSet<>();
        if(categoryId != null) {
            categoryService.findSubCategoryId(categoryId, categoryIdSet);
            categoryIdSet.add(categoryId);
        }
    
        PageHelper.startPage(pageNum, pageSize);
        List<Product> productList = productMapper.selectByCategoryIdSet(categoryIdSet);
        List<ProductVo> productVoList = productList.stream()
                .map(e -> {
                    ProductVo productVo = new ProductVo();
                    BeanUtils.copyProperties(e, productVo);
                    return productVo;
                })
                .collect(Collectors.toList());
    
        PageInfo pageInfo = new PageInfo<>(productList);
        pageInfo.setList(productVoList);
        return ResponseVo.success(pageInfo);
    }
    
    /**
     * 商品详情
     *
     * @param productId
     * @return
     */
    @Override
    public ResponseVo<ProductDetailVo> detail(Integer productId) {
        ProductDetailVo productDetailVo = new ProductDetailVo();
        Product product = productMapper.selectByPrimaryKey(productId);
    
        //只对确定性条件判断
        if (product.getStatus().equals(OFF_SALE.getCode())
                || product.getStatus().equals(DELETE.getCode())) {
            return ResponseVo.error(PRODUCT_OFF_SALE_OR_DELETE);
        }
        
        BeanUtils.copyProperties(product, productDetailVo);
    
        //敏感数据处理
        productDetailVo.setStock(product.getStock() > 100 ? 100 : product.getStock());
        
        return ResponseVo.success(productDetailVo);
    }
}
